<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="500px"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm">
      <template #menus="{ model, field }">
<!--        <BasicTree-->
<!--          v-model:value="model[field]"-->
<!--          :treeData="treeData"-->
<!--          :treeDataSimpleMode=false-->
<!--          checkable-->
<!--          toolbar-->
<!--          id="caidan"-->
<!--          title="菜单分配"-->
<!--        />-->
        <a-tag color="#55acee">
          分配菜单
        </a-tag>
        <a-tree-select
          v-model:value="model[field]"
          style="width: 100%"
          :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
          :tree-data="treeData"
          treeDataSimpleMode
          placeholder="Please select"
          tree-checkable
          allow-clear
          tree-default-expand-all
          title="菜单分配"
        >
         <!-- tree-default-expand-all-->

        </a-tree-select>
      </template>


      <template #apis="{ model, field }">

        <a-tag color="#55acee">
          分配api
        </a-tag>
        <a-tree-select
          v-model:value="model[field]"
          style="width: 100%"
          :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
          :tree-data="treeDataApi"
          treeDataSimpleMode
          placeholder="Please select"
          tree-checkable
          allow-clear
          tree-default-expand-all
          title="分配api"
        >
          <!-- tree-default-expand-all-->

        </a-tree-select>
      </template>
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema } from './role.data';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { BasicTree, TreeItem } from '/@/components/Tree';
  import {
    createMenu,
    createRole, getApiList, getApiListAll,
    getMenuList,
    getMenuListAll,
    updateMenu,
    updateRole
  } from '/@/api/demo/system';
  import {useMessage} from "@/hooks/web/useMessage";
  import {useTree} from "@/components/Tree/src/hooks/useTree";

  const emit = defineEmits(['success', 'register']);
  const isUpdate = ref(true);
  const treeData = ref<TreeItem[]>([]);
  const treeDataApi = ref<TreeItem[]>([]);

  const [registerForm, { resetFields, setFieldsValue, validate,getFieldsValue }] = useForm({
    labelWidth: 90,
    baseColProps: { span: 24 },
    schemas: formSchema,
    showActionButtonGroup: false,
  });

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    resetFields();
    setDrawerProps({ confirmLoading: false });
    // 需要在setFieldsValue之前先填充treeData，否则Tree组件可能会报key not exist警告
    if (unref(treeData).length === 0) {
      treeData.value = (await getMenuListAll()) as any as TreeItem[];
    }
    if (unref(treeDataApi).length === 0) {
      treeDataApi.value = (await getApiListAll()) as any as TreeItem[];
    }
    isUpdate.value = !!data?.isUpdate;

    if (unref(isUpdate)) {
      setFieldsValue({
        ...data.record,
      });
    }
  });

  const getTitle = computed(() => (!unref(isUpdate) ? '新增角色' : '编辑角色'));

  async function handleSubmit() {
    try {
      const values = await validate();
      setDrawerProps({ confirmLoading: true });
      // TODO custom api
      var menuFunc = createRole
      if (unref(isUpdate)) {



        menuFunc = updateRole
      }
      // 发起请求
      // 判断一下menus的类型

      // 这里是给前端用的
      var reqData =  getFieldsValue()
      var menus = reqData["menus"]
      var menuIds = []
      if (menus!=null && menus.length>0){
        menus.forEach((val, idx, array) => {

          if (val.id !=null){
            menuIds.push(val.id)

          }else {
            menuIds.push(val)
          }

        })
      }

      var apis = reqData["apis"]
      var apiIds = []
      if (apis!=null) {
        apis.forEach((val, idx, array) => {

          if (val.id != null) {
            apiIds.push(val.id)

          } else {
            apiIds.push(val)
          }

        })
      }




      delete reqData["menus"]
      reqData["menuIds"] = menuIds


      delete reqData["apis"]
      reqData["apiIds"] = apiIds


      const { createMessage } = useMessage();
      menuFunc(reqData).then(() => {
        createMessage.success(`${getTitle.value}成功`);
      }).catch(() => {
        createMessage.error(`${getTitle.value}失败`);
      })


      console.log(values);
      closeDrawer();
      emit('success');
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
